package icu.lookyousmileface.concurrentutils;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author starrysky
 * @title: SemaphoreUse
 * @projectName Juc_Pro
 * @description:
 * @date 2021/1/292:38 下午
 */
public class SemaphoreUse {
    public static void main(String[] args) {
        //可以用来限制流量
        Semaphore semaphore = new Semaphore(3);

        for (int i = 1; i <= 6; i++) {
            new Thread(()->{
                try {
                    //关闸
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"入库");
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println(Thread.currentThread().getName()+"离开");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    //开闸
                    semaphore.release();
                }
            },String.valueOf(i)).start();
        }
    }
}
